package com.jinyang.jetpackdemo.hilt

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.jinyang.jetpackdemo.R
import com.jinyang.jetpackdemo.util.LjyLogUtil
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.activity_hilt_mvvm.*
import kotlinx.coroutines.*
import java.text.SimpleDateFormat
import java.util.*
import javax.inject.Inject

@AndroidEntryPoint
class HiltMvvmActivity : AppCompatActivity() {

//    @Inject
//    lateinit var viewModel: MyViewModel

    val viewModel: MyViewModel by viewModels()
//    val viewModel: MyViewModel by lazy { ViewModelProvider(this).get(MyViewModel::class.java) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_hilt_mvvm)
        viewModel.result.observe(this, Observer {
            LjyLogUtil.d("result:$it")
        })
        viewModel.doWork()
        val mainScope = MainScope()
        btn.setOnClickListener {
            mainScope.launch {
                log("1")
                btn.text = async(Dispatchers.IO) {
                    log("2")
                    delay(1000)
                    log("3")
                    "hello"
                }.await()
                log("4")
            }
        }
    }
}

@SuppressLint("SimpleDateFormat")
val dateFormat = SimpleDateFormat("HH:mm:ss:SSS")
val now = {
    dateFormat.format(Date(System.currentTimeMillis()))
}

fun log(msg: Any?) = LjyLogUtil.d("${now()} [${Thread.currentThread().name}] $msg")